package com.xiaoq.matrix.endpoint;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.RedisTemplate4JedisCluster;
import com.xiaoq.apis.sites.ISitesApi;
import com.xiaoq.apis.sites.SitesInfo4Activity;
import com.xiaoq.apis.user.MerchantMgrInfo4Vo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.coms.util.JsonUtil;
import com.xiaoq.coms.util.MapUtil;
import com.xiaoq.matrix.entity.ContentElementEntity;
import com.xiaoq.matrix.entity.ContentEntity;
import com.xiaoq.matrix.entity.ContentMediaAccountEntity;
import com.xiaoq.matrix.entity.ContentMediaEntity;
import com.xiaoq.matrix.minipro.service.impl.MiniProServiceImpl;
import com.xiaoq.matrix.service.IContentElementService;
import com.xiaoq.matrix.service.IContentMediaAccountService;
import com.xiaoq.matrix.service.IContentMediaService;
import com.xiaoq.matrix.service.IContentService;
import com.xiaoq.matrix.service.IMerchantMgrService;
import com.xiaoq.matrix.toutiao.util.TouTiaoException;
import com.xiaoq.matrix.toutiao.util.TouTiaoOauth;
import com.xiaoq.matrix.vo.ContentAndElementVo;
import com.xiaoq.matrix.vo.ContentElementVo;
import com.xiaoq.matrix.vo.ContentMediaVo;
import com.xiaoq.matrix.vo.ContentStaticResponseVo;
import com.xiaoq.matrix.vo.ContentVo;
import com.xiaoq.matrix.vo.PublishTaskVo;
import com.xiaoq.matrix.vo.ReptileVo;
import com.xiaoq.matrix.vo.UnAuthorizedItemVo;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;
import com.xiaoq.sensitive.SensitivewordFilterUtil;
import com.xiaoq.vo.PagingVo;
import com.xiaoq.web.HttpsRestTemplate;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import weibo4j.Oauth;
import weibo4j.model.WeiboException;

@RestController
@RequestMapping("/api/v1/content")
public class ContentEndpoint2B {
	private static final Logger LOG = LoggerFactory.getLogger(ContentEndpoint2B.class);
	private static final class MediaAuthorizeUrlResponse extends GenericDataResponse<String> {};
	private static final class ContentElementListResponse extends GenericListResponse<ContentElementVo> {};
	private static final class ContentListResponse extends GenericListResponse<ContentVo> {};
	private static final class ContentDataResponse extends GenericDataResponse<ContentEntity> {};
	private static final class ContentPubResponse extends GenericListResponse<UnAuthorizedItemVo> {};
	private static final class ContentMediaListResponse extends GenericListResponse<ContentMediaVo> {};
	@Autowired
	private IContentMediaAccountService contentMediaAccountSrv;
	
	@Autowired
	private IContentMediaService contentMediaSrv;
	
	@Autowired
	private IContentElementService contentElementSrv;
	
	@Autowired
	private IContentService contentSrv;
	
	@Autowired
	private MiniProServiceImpl miniProService;
	
	@Autowired
	private IdGenerator idGenerator;
	
	@Autowired
	private IMerchantMgrService merMgerSrv;
	
	@Autowired
	private HttpsRestTemplate rest;
	
	@Autowired
	private RedisTemplate4JedisCluster redisTemplate;
	
	@Reference(interfaceClass=ISitesApi.class,check=false,version="1.0.0")
	private ISitesApi sitesApi;
	
	@Value("${yunyingAdress}")
	private String yunyingAdress;
	
	@ApiOperation(value = "获取媒体平台授权URL", notes = "获取媒体平台授权URL")
	@ApiResponses({ @ApiResponse(code = 200, response = MediaAuthorizeUrlResponse.class, message = "获取媒体平台授权URL") })
	@GetMapping(value = "/authorizeurl/{mediaName}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> authorizeUrl(@RequestParam(value = "userId", required = true)@ApiParam(value="userId",required=true) String userId,
			@PathVariable(value = "mediaName", required = true)@ApiParam(value="mediaName(新浪微博/今日头条/微信)",required=true)String mediaName) {
		// 根据mediaName查询要绑定到那个媒体
		// 获取对应媒体的开发者账号配置
		// 返回媒体开放平台的授权url
		String authorizeUrl = authorizeUrlMethod(userId,mediaName);
		return MediaAuthorizeUrlResponse.okWithData(authorizeUrl);
	}
	
	@ApiOperation(value = "收回媒体平台授权", notes = "收回媒体平台授权")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "收回媒体平台授权") })
	@DeleteMapping(value = "/unbind/{mediaName}", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> unbindMedia(@RequestParam(value = "userId", required = true) String userId,
			@PathVariable(value = "mediaName", required = true) String mediaName) {
		// 删除对应的账号绑定关系
		ContentMediaEntity contentMedia = contentMediaSrv.findContentMedia(mediaName);
		if(contentMedia!=null){
			String mediaId = contentMedia.getId();
			boolean result = contentMediaAccountSrv.delMediaAccount(userId, mediaId);
			if(result){
				return GenericResponse.ok();
			}
			
		}
		return GenericResponse.ng("授权失败！");
	}
	
	@ApiOperation(value = "获取素材列表", notes = "获取素材列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentElementListResponse.class, message = "获取素材列表") })
	@GetMapping(value = "/element/ofuser", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentElementList(@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "pubStart", required = false) Long pubStart,
			@RequestParam(value = "pubEnd", required = false) Long pubEnd,
			@ModelAttribute(value="pvo")PagingVo pvo) {
		
		ContentAndElementVo contentAndElementVo = new ContentAndElementVo();
		contentAndElementVo.setUserId(userId);
		contentAndElementVo.setName(name);
		contentAndElementVo.setPubStart(pubStart);
		contentAndElementVo.setPubEnd(pubEnd);
		List<ContentElementEntity> contentElementList = contentElementSrv.findContentElementList(contentAndElementVo, pvo);
		Long total = pvo.getTc().longValue();
		List<ContentElementVo> contentElementVoList = new ArrayList<>();
		ContentElementVo contentElementVo = null;
		if(CollectionUtils.isNotEmpty(contentElementList)){
			for(ContentElementEntity contentElement:contentElementList){
				contentElementVo = new ContentElementVo();
				BeanUtils.copyProperties(contentElement, contentElementVo);
				contentElementVoList.add(contentElementVo);
			}
			
			
		}else{
			LOG.info("查询结果为空");	
		}
		return ContentElementListResponse.listAndCount(contentElementVoList, total);
		
	}
	
	@ApiOperation(value = "添加素材", notes = "添加素材")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加素材") })
	@PostMapping(value = "/element", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addContentElement(@ModelAttribute(value="contentElementVo")ContentElementVo contentElementVo, @RequestParam(value="file") MultipartFile file) {
		// 需要注意素材类型，image/vedio等
		if(file!=null){
			contentElementVo.setId(idGenerator.nextId());
			ContentElementEntity contentElementEntity = new ContentElementEntity();
			BeanUtils.copyProperties(contentElementVo, contentElementEntity);
			if (StringUtils.isBlank(contentElementEntity.getExt())) {
				contentElementEntity.setExt(FileUtils.getFileExtension(new File(file.getOriginalFilename())));
			}
			String imgUrl = null;
			try {
				imgUrl = UploadUtil.easyUploadByte(file,
				        QiNiuSpaceEnum.XIAOQ_MATRIX.getName().toLowerCase(), QiNiuSpaceEnum.XIAOQ_MATRIX.getDomain());
				LOG.info("添加素材在青牛云上的地址："+imgUrl);
				if(imgUrl!=null){
					contentElementEntity.setUrl(imgUrl);
					boolean result = contentElementSrv.addContentElement(contentElementEntity);
					if(result){
						return GenericResponse.ok();
					}
				}
				
			} catch (IOException e) {
				LOG.error("素材上传七牛云出错！", e);
				return GenericResponse.ng("素材上传七牛云失败请重新上传！");
			}
			
		}
		
		
		return GenericResponse.ng("添加素材失败,请重新上传！");
	}
	
	@ApiOperation(value = "获取内容列表", notes = "获取内容列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentListResponse.class, message = "获取内容列表") })
	@GetMapping(value = "/ofuser", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentList(
			@RequestParam(value = "title", required = false) String title,
			@RequestParam(value = "pubStart", required = false) Long pubStart,
			@RequestParam(value = "pubEnd", required = false) Long pubEnd,
			@RequestParam(value = "pubStatus", required = false)@ApiParam(value="0待审核1已发布,2已经分发,3审核失败", required = false)String pubStatus,
			@ModelAttribute(value="pvo")PagingVo pvo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		ContentAndElementVo contentAndElementVo = new ContentAndElementVo();
		contentAndElementVo.setTitle(title);
		contentAndElementVo.setShopId(shopId);
		contentAndElementVo.setPubStart(pubStart);
		contentAndElementVo.setPubEnd(pubEnd);
		contentAndElementVo.setPubStatus(pubStatus);
		List<ContentEntity> contentList = contentSrv.findContentElementList(contentAndElementVo, pvo);
		Long total = pvo.getTc().longValue();
		List<ContentVo> contentVoList = new ArrayList<>();
		ContentVo contentVo = null;
		if(contentList!=null){
			for(ContentEntity content: contentList){
				contentVo = new ContentVo();
				BeanUtils.copyProperties(content, contentVo);
				contentVoList.add(contentVo);
			}
		}
		
		return ContentListResponse.listAndCount(contentVoList, total);
		
	}

	@ApiOperation(value = "对接爬虫", notes = "对接爬虫")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "对接爬虫") })
	@PostMapping(value = "/reptile", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> reptileAdapter(@RequestBody ReptileVo reptileVo) {
		boolean result = true;
		String title = reptileVo.getTitle();
		if(title==null){
			String result1 = SensitivewordFilterUtil.filter(title);
			if(StringUtils.isNotBlank(result1)){
				return GenericResponse.ng(result1);
			}
			result=false;
		}
		String imgUrl = reptileVo.getImgUrl();
		if(imgUrl==null){
			result=false;
		}
		String introduction = reptileVo.getIntroduction();
		if(introduction==null){
			String result1 = SensitivewordFilterUtil.filter(introduction);
			if (StringUtils.isNotBlank(result1)) {
				return GenericResponse.ng(result1);
			}
			result=false;
		}
		String staticPath = reptileVo.getStaticPath();
		if(staticPath==null){
			result=false;
		}
		String zoneCity = reptileVo.getZoneCity();
		if(zoneCity==null){
			result=false;
		}
		String detailInfo = reptileVo.getDetailInfo();
		if(detailInfo==null){
			String result1 = SensitivewordFilterUtil.filter(detailInfo);
			if(StringUtils.isNotBlank(result1)){
				return GenericResponse.ng(result1);
			}
			result=false;
		}
		if(result){
			ContentEntity contentEntity = new ContentEntity();
			BeanUtils.copyProperties(reptileVo, contentEntity);
			contentEntity.setId(idGenerator.nextId());
			contentEntity.setPubTime(System.currentTimeMillis());
			contentEntity.setPubStatus("1");
			contentEntity.setShareNum(0);
			contentSrv.addContent(contentEntity);
		}
		return GenericResponse.ok();

	}
	
	@ApiOperation(value = "添加内容", notes = "添加内容")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "添加内容") })
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addContent(@RequestBody ContentVo contentVo,HttpServletRequest request) {
		String userId = (String) request.getAttribute("userId");
		LOG.info("添加内容时的管理员Id"+userId);
		MerchantMgrInfo4Vo merchantMgr = merMgerSrv.findMerMger(userId);
		String merChantId = merchantMgr.getMerchantId();
		if(StringUtils.isEmpty(merChantId)){
			return GenericResponse.ng("商店认证之后才能发内容！");
		}
		String shopId = merchantMgr.getShopId();
		if(StringUtils.isEmpty(shopId)){
			return GenericResponse.ng("管理员创建景区后才能发布内容！");
		}
		String title = contentVo.getTitle();
		if(StringUtils.isBlank(title)){
			return GenericResponse.ng("标题不能为空");
		}else{
			String result = SensitivewordFilterUtil.filter(title);
			if(StringUtils.isNotBlank(result)){
				return GenericResponse.ng(result);
			}
		}
		String htmlUrl = null;
		if (contentVo != null) {
			try {
				String detailInfo = contentVo.getDetailInfo();
				if(StringUtils.isBlank(detailInfo)){
					return GenericResponse.ng("内容不能为空");
				}else{
					String result = SensitivewordFilterUtil.filter(detailInfo);
					if(StringUtils.isNotBlank(result)){
						return GenericResponse.ng(result);
					}
				}
				String content = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>小Q旅游</title></head><body>"
						+detailInfo+"</body></html>";
				if (StringUtils.isNotEmpty(detailInfo)) {
					content = contetnAdapter(content);
					htmlUrl = contentStaticize(content);
					contentVo.setStaticPath(htmlUrl);
				} else {
					return GenericResponse.ng("文章内容为空！");
				}
				String imgUrl = contentVo.getImgUrl();
				if(StringUtils.isBlank(imgUrl)){
					contentVo.setImgUrl("http://p0sd9v5tn.bkt.clouddn.com/MTcxNDU0NTQyMjI5NDI2NzE1MjA5Mjg1NjQxNzM=");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			ContentEntity contentEntity = new ContentEntity();
			BeanUtils.copyProperties(contentVo, contentEntity);
			String introduction = contentEntity.getIntroduction();
			// 如果内容简介不发布的话默认截取内容详情的先54个字符
			if(StringUtils.isEmpty(introduction)){
				String detailInfo = contentEntity.getDetailInfo();
				if(detailInfo.length()>54){
					introduction = detailInfo.substring(0, 54);
				}else{
					introduction = detailInfo;
				}
				
				contentEntity.setIntroduction(introduction);
			} else {

				String result = SensitivewordFilterUtil.filter(introduction);
				if (StringUtils.isNotBlank(result)) {
					return GenericResponse.ng(result);
				}

			}
			SitesInfo4Activity sitesInfo = sitesApi.getSitesInfo4Activity(shopId);
			if(sitesInfo==null){
				return GenericResponse.ng("店铺不存在！");
			}
			contentEntity.setId(idGenerator.nextId());
			contentEntity.setShopId(shopId);
			contentEntity.setShopType(merchantMgr.getShopType());
			contentEntity.setCreatedBy(userId);
			contentEntity.setMerchantId(merChantId);
			contentEntity.setPubTime(System.currentTimeMillis());
			contentEntity.setStaticPath(htmlUrl);
			contentEntity.setPubStatus("0");
			contentEntity.setShareNum(0);
			contentEntity.setZoneProvince(sitesInfo.getZoneProvince());
			contentEntity.setZoneCity(sitesInfo.getZoneCity());
			contentEntity.setZoneProvince(sitesInfo.getZoneDistrict());
			boolean result = contentSrv.addContent(contentEntity);
			if (result) {
				try {
					submitVarify(contentEntity, sitesInfo);
				} catch (Exception e) {
					LOG.error(e.getMessage(),e);
				}
//				JsonUtil.asObject(respStr, MiniProComponentToken.class);	
				return GenericResponse.ok();
			}
		}

		return GenericResponse.ng("添加内容失败");
	}
	
	@Async
	public boolean submitVarify(ContentEntity contentEntity,SitesInfo4Activity sitesInfo){
		Map<String, Object> body = MapUtil.buildMapKVGen(
			new Object[][] { { "businessId", sitesInfo.getId() }, 
				{"businessName", sitesInfo.getName() },
				{"content", contentEntity.getDetailInfo()},
				{"formerId", contentEntity.getId() },
				{"introduction", contentEntity.getIntroduction()},
				{"mainImage", contentEntity.getImgUrl()},
				{"title", contentEntity.getTitle()}},
			String.class,
			Object.class);
	LOG.info(yunyingAdress+"/admin/xqArticle");

	String respStr = post(yunyingAdress+"/admin/xqArticle", body);
	LOG.info(respStr);
		return true;
		
	}
	
	@ApiOperation(value = "对接运营后端（内容的审核）", notes = "对接运营后端（内容的审核）")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "对接运营后端（内容的审核）") })
	@PutMapping(value = "/status", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> verifyContent(@ApiParam(value="文章Id",required=true)@RequestParam(value="contentId",required=true)String contentId,@ApiParam(value="审核状态2表示审核成功3表示审核失败")@RequestParam(value="pubStatus",required=true)String pubStatus){
		contentSrv.updateContentStatus(contentId, pubStatus);
		return GenericResponse.ok();
		
	}

	@ApiOperation(value = "获取内容详情", notes = "获取内容详情")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentDataResponse.class, message = "获取内容详情") })
	@GetMapping(value = "detail", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentDetail(@RequestParam(value="id",required=true)@ApiParam(value="内容Id",required=true) String id) {
		LOG.info(id);
		ContentEntity content = null;
		content = contentSrv.findContent(id);
		if(content==null){
			LOG.info("查询结果为空");
		}
		return ContentDataResponse.okWithData(content);
	}
	/**
	 * 修改内容对静态页面做更新在repository层实现
	 * @param contentVo
	 * @return
	 */
	@ApiOperation(value = "修改内容", notes = "修改内容")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "修改内容") })
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> updateContent(@RequestBody ContentVo contentVo) {
		String htmlUrl = null;
		if(contentVo!=null){
			String title = contentVo.getTitle();
			if(StringUtils.isNotBlank(title)){
				String result = SensitivewordFilterUtil.filter(title);
				if(StringUtils.isNotBlank(result)){
					return GenericResponse.ng(result);
				}
			}
			String detailInfo = contentVo.getDetailInfo();
			if (StringUtils.isNotBlank(detailInfo)) {
				String result = SensitivewordFilterUtil.filter(detailInfo);
				if (StringUtils.isNotBlank(result)) {
					return GenericResponse.ng(result);
				}
				String content = "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>小Q旅游</title></head><body>"
						+ detailInfo + "</body></html>";
				content = contetnAdapter(content);
				htmlUrl = contentStaticize(content);
				contentVo.setStaticPath(htmlUrl);
			}
			String intruduction = contentVo.getIntroduction();
			if(StringUtils.isNotBlank(intruduction)){
				String result = SensitivewordFilterUtil.filter(intruduction);
				if(StringUtils.isNotBlank(result)){
					return GenericResponse.ng(result);
				}
			}
			ContentEntity content  = new ContentEntity();
			BeanUtils.copyProperties(contentVo, content);
			boolean result = contentSrv.updateContent(content);
			if(result){
				return GenericResponse.ok();
			}
		}
		
		return GenericResponse.ng("更新失败");
	}
	
	@ApiOperation(value = "删除内容", notes = "删除内容")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "根据内容Id删除内容") })
	@DeleteMapping(value = "", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> deleteContent(@RequestParam(value="id",required=true)String id) {
		LOG.info(id);
		boolean result = contentSrv.delContent(id);
		if(result){
			return GenericResponse.ok();
		}
		return GenericResponse.ng("删除出错！");
	}
	
	@ApiOperation(value = "发布内容", notes = "发布内容")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentPubResponse.class, message = "添加内容") })
	@PostMapping(value = "/status:pub", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> pubContent(@RequestParam(value="mediaList",required = true) @ApiParam(value="媒体的id列表") List<String> mediaList,
			@RequestParam(value="id",required=true) String id,
			HttpServletRequest request) {
		// 首先验证对应的媒体账号的access_token是否有效，如果无效则返回需要重新授权的提示对象，同时将响应码设置为1000，页面发现1000响应后发起授权操作
		// {
		//   rc: "1000",
		//   msg: "授权已过期，需要重新授权",
		//   list: [{
		//     mediaName: "今日头条",
		//     authorizeUrl: "https://open.snssdk.com/auth/authorize/?x=1&y=2&z=3....."
		//   }, {}
		// 如果所有的access_token都有效，则将任务添加到MQ，随即返回，留给后续异步处理
		// 页面上如果想查看任务执行情况，可以通过查询内容详情获取
		// MQ任务的处理逻辑如下：
		// 获取任务详情-->根据同步媒体列表属性一次将内容同步过去，完成一个同步后更新对应状态
		String userId = (String) request.getAttribute("userId");
		LOG.info("管理员Id"+userId+"媒体列表"+mediaList);
		ContentEntity ce = contentSrv.findContent(id);
		if (ce == null) {
			return GenericResponse.ng("找不到内容");
		}
		
		String merchantId = ce.getMerchantId();
		if(StringUtils.isEmpty(merchantId)){
			return GenericResponse.ng("管理员没有对应的商店！");
		}
		String shopId = ce.getShopId();
		if(StringUtils.isEmpty(shopId)){
			return GenericResponse.ng("管理员没有注册对应店铺！");
		}
		List<UnAuthorizedItemVo> unAuthorizedItemVoList=new ArrayList<>();
		List<String> accessTokenList = new ArrayList<String>();
		for(String mediaId:mediaList){
			//TODO 微信的Id可能会发生改变
			// 微信和其他两种的授权方式不一样所以分开处理
			if("contentmedia003".equals(mediaId)){
				String accessToken = miniProService.getAccessTokenByShopId(shopId,"1");
				LOG.info("同步到微信上的第三方Token为"+accessToken);
				if(StringUtils.isNotEmpty(accessToken)){
					accessTokenList.add(accessToken);
				}else{
					ContentMediaEntity contentMedia = contentMediaSrv.getContentMediaById(mediaId);
					LOG.info("contentMedia:  "+contentMedia);
					UnAuthorizedItemVo unAuthorizedVo = new UnAuthorizedItemVo();
					String name = contentMedia.getName();
					unAuthorizedVo.setMediaName(name);
					String authorizeUrl ="https://matrix.xiaoq.online/api/v1/auth?userId="+userId+"&type=1";
					unAuthorizedVo.setAuthorizeUrl(authorizeUrl);
					unAuthorizedItemVoList.add(unAuthorizedVo);
				}
				
			}else{
				LOG.info("商户Id"+merchantId+"媒体Id"+mediaId);
				ContentMediaAccountEntity contentMediaAccount = contentMediaAccountSrv.findContentMediaAccount(merchantId, mediaId);
				LOG.info("contentMediaAccount: "+contentMediaAccount);
				LOG.info("mediaId:" +mediaId);
				ContentMediaEntity contentMedia = contentMediaSrv.getContentMediaById(mediaId);
				if(contentMedia==null){
					LOG.error("不存在"+mediaId+"对应的媒体！");
					return GenericResponse.ng("不存在"+mediaId+"对应的媒体！");
				}
				LOG.info("contentMedia:  "+contentMedia);
				String name = contentMedia.getName();
				LOG.info("媒体名称："+name);
				String authorizeUrl = authorizeUrlMethod(userId,name);
				if(contentMediaAccount!=null){
					long tokenTime = contentMediaAccount.getTokenTime();
					long tokenDuratio = contentMediaAccount.getTokenDuratio();
					long total =tokenTime+tokenDuratio;
					long currentTime = System.currentTimeMillis();
					//表示Token过期
					if(total<currentTime){
						UnAuthorizedItemVo unAuthorizedVo = new UnAuthorizedItemVo();
						unAuthorizedVo.setMediaName(name);
						unAuthorizedVo.setAuthorizeUrl(authorizeUrl);
						unAuthorizedItemVoList.add(unAuthorizedVo);
					}else{
						String access_token = contentMediaAccount.getToken();
						accessTokenList.add(access_token);
					}
				}else{
					UnAuthorizedItemVo unAuthorizedVo = new UnAuthorizedItemVo();
					unAuthorizedVo.setMediaName(name);
					unAuthorizedVo.setAuthorizeUrl(authorizeUrl);
					unAuthorizedItemVoList.add(unAuthorizedVo);
				}
				
			}
			
		}
		if(unAuthorizedItemVoList.size()!=0){
			LOG.info("媒体信息存在过期token！");
			String rc = "1000";
			String msg = "授权已过期，需要重新授权";
			return ContentPubResponse.listNoCount(rc,msg,unAuthorizedItemVoList);
		}
		
		
		Long time = System.currentTimeMillis();
		
		PublishTaskVo task = new PublishTaskVo();
		task.setAccessTokenList(accessTokenList);
		task.setContentId(id);
		task.setSubmitTime(time);
		task.setMediaIdList(mediaList);
		task.setMerchantId(merchantId);
		task.setUserId(userId);
		
		contentSrv.sendPublishMessage(JsonUtil.asString(task));
		ContentEntity entity = contentSrv.findContent(id);
		entity.setPubStatus("2");
		contentSrv.addContent(entity);
		
		return ContentPubResponse.ok();
	}
	
	
	private String authorizeUrlMethod(String userId,String mediaName){
		String authorizeUrl = null;
		if(mediaName.equals("新浪微博")){
			Oauth oauth = new Oauth();
			try {
				authorizeUrl = oauth.authorize("code",userId);
			} catch (WeiboException e) {
				LOG.error("请求地址转换格式异常！", e);
			}
		}
		if(mediaName.equals("今日头条")){
			TouTiaoOauth oauth =new TouTiaoOauth();
			try {
				authorizeUrl = oauth.authorize("code",userId);
			} catch (TouTiaoException e) {
				LOG.error("今日头条地址转化格式异常！", e);
			}
		}
		return authorizeUrl;
	}
	
	@ApiOperation(value = "获取媒体列表", notes = "获取媒体列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentMediaListResponse.class, message = "获取媒体列表") })
	@GetMapping(value = "/con_meidas", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> getContentMedia(){
		
		List<ContentMediaEntity> contentMediaList =  contentMediaSrv.getContentMedias();
		List<ContentMediaVo> contentMediaVoList = new ArrayList<>();
		ContentMediaVo contentMediaVo = null;
		for(ContentMediaEntity contentMedia:contentMediaList){
			contentMediaVo = new ContentMediaVo();
			BeanUtils.copyProperties(contentMedia, contentMediaVo);
			contentMediaVoList.add(contentMediaVo);
		}
		return ContentMediaListResponse.listNoCount(contentMediaVoList);
		
	}
	
	private String post(String url, Map<String, Object> body) {
		HttpEntity<Map<String, Object>> reqEntity = new HttpEntity<>(body);
		String respStr = null;
		try {
			respStr = rest.postForObject(new URI(url), reqEntity, String.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return respStr;
	}
	@ApiOperation(value = "添加内容测试", notes = "添加内容测试")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericDataResponse.class, message = "添加内容测试") })
	@PostMapping(value = "/content", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> addContentTest(
			@RequestBody String content) {
		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "content", content }}, String.class,
				Object.class);
		String respStr = post("https://share.xiaoq.online/api/v1/share/content", body);
		ContentStaticResponseVo contentStaticVo = JsonUtil.asObject(respStr, ContentStaticResponseVo.class);
		return GenericDataResponse.okWithData(contentStaticVo.getData());

	}


	@ApiOperation(value = "根据标题搜索获取内容列表", notes = "根据标题搜索获取内容列表")
	@ApiResponses({ @ApiResponse(code = 200, response = ContentListResponse.class, message = "根据标题搜索获取内容列表") })
	@GetMapping(value = "/search", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> contentList(
			@RequestParam(value = "title", required = true) String title,
			@ApiParam(value="页码,从1开始", required=false) @RequestParam(defaultValue = "1") int pn,
			@ApiParam(value="条数", required=false) @RequestParam(defaultValue = "10") int ps,
			HttpServletRequest request) {

		String userId = (String) request.getAttribute("userId");
		String shopId = redisTemplate.get(ConstantUtil.REDIS_PREFIX_MANAGER_SHOP_RELATION, userId);
		PagingVo pagingVo = new PagingVo(pn-1, ps);
		List<ContentEntity> contentList = contentSrv.findContentListFromEs(shopId, title, pagingVo);
		List<ContentVo> contentVoList = new ArrayList<>();
		ContentVo contentVo;
		if(contentList!=null){
			for(ContentEntity content: contentList){
				contentVo = new ContentVo();
				BeanUtils.copyProperties(content, contentVo);
				contentVoList.add(contentVo);
			}
		}

		return ContentListResponse.listNoCount(contentVoList);

	}

	
	private String contetnAdapter(String content){
		Document doc = Jsoup.parseBodyFragment(content);
		Elements ImageElements =doc.select("img");
		for (Element imgElement : ImageElements) {
			String imageUrl = imgElement.attr("src");
			if (!StringUtils.isEmpty(imageUrl)) {
				if (!StringUtils.isEmpty(imgElement.attr("width"))) {
					ImageElements.attr("width", "100%");
				}
				if (!StringUtils.isEmpty(imgElement.attr("height"))) {
					ImageElements.attr("height", "auto");
				}
				String styleStr = imgElement.attr("style");
				if (!StringUtils.isEmpty(styleStr)) {
					if (styleStr.indexOf(";width") != -1) {
						String wFrontStr = styleStr.substring(0, styleStr.indexOf(";width") + 7);
						String wMiddleStr = styleStr.substring(styleStr.indexOf(";width") + 7,
								styleStr.length());
						String wNextStr = wMiddleStr.substring(wMiddleStr.indexOf(";"),
								wMiddleStr.length());
						styleStr = wFrontStr + "100%" + wNextStr;
					} else if (styleStr.indexOf("; width") != -1) {
						String wFrontStr = styleStr.substring(0, styleStr.indexOf("; width") + 8);
						String wMiddleStr = styleStr.substring(styleStr.indexOf("; width") + 8,
								styleStr.length());
						String wNextStr = wMiddleStr.substring(wMiddleStr.indexOf(";"),
								wMiddleStr.length());
						styleStr = wFrontStr + "100%" + wNextStr;
					} else {
						styleStr = styleStr + "width:100%;";
					}
					if (styleStr.indexOf("height") != -1) {
						String hFrontStr = styleStr.substring(0, styleStr.indexOf("height") + 7);
						String hMiddleStr = styleStr.substring(styleStr.indexOf("height") + 7,
								styleStr.length());
						String hNextStr = hMiddleStr.substring(hMiddleStr.indexOf(";"),
								hMiddleStr.length());
						styleStr = hFrontStr + "auto" + hNextStr;
					} else {
						styleStr = styleStr + "height:auto;";
					}
					ImageElements.attr("style", styleStr);
				} else {
					ImageElements.attr("style", "height: auto;width: 100%;");
				}
			}
		}
		content = doc.html();
		return content;
		
	}
	
	private String contentStaticize(String content){
		Map<String, Object> body = MapUtil.buildMapKVGen(
				new Object[][] { { "content", content }}, String.class,
				Object.class);
		HttpEntity<Map<String, Object>> reqEntity = new HttpEntity<>(body);
		String respStr = null;
		try {
			respStr = rest.postForObject(new URI("https://share.xiaoq.online/api/v1/share/content"), reqEntity, String.class);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		ContentStaticResponseVo contentStaticVo = JsonUtil.asObject(respStr, ContentStaticResponseVo.class);
		String url = contentStaticVo.getData();
		return url;
		
	}
	
}
